# coding = utf-8
import urllib.request
import re
import requests
import os
import json


def getDatas(keyword, pages):
    params = []
    for i in range(30, 30*pages+30, 30):
        params.append({
                      'tn': 'resultjson_com',
                      'ipn': 'rj',
                      'ct': 201326592,
                      'is': '',
                      'fp': 'result',
                      'queryWord': keyword,
                      'cl': 2,
                      'lm': -1,
                      'ie': 'utf-8',
                      'oe': 'utf-8',
                      'adpicid': '',
                      'st': -1,
                      'z': '',
                      'ic': 0,
                      'word': keyword,
                      's': '',
                      'se': '',
                      'tab': '',
                      'width': '',
                      'height': '',
                      'face': 0,
                      'istype': 2,
                      'qc': '',
                      'nc': 1,
                      'fr': '',
                      'pn': i,
                      'rn': 30,
                      'gsm': '1e',
                      '1526377465547': ''
                      })
    url = 'https://image.baidu.com/search/index'
    headers = {
        # 'Accept': 'application/json, text/javascript, */*; q = 0.01',
        # 'Accept-Encoding': 'gzip, deflate, br',
        # 'Accept-Language': 'zh-CN,zh;q=0.9',
        # 'cache-control': 'max-age=0',
        'referer': 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1547737308684_R&pv=&ic=&nc=1&z=&hd=&latest=&copyright=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E8%A1%97%E6%8B%8D',
        # 'upgrade-insecure-requests': '1',
        'cookie': 'BDIMGISLOGIN=0; BDqhfp=%E8%A1%97%E6%8B%8D%26%26-10-1undefined%26%26355%26%262; BDUSS=UNyejFFaHBnVEVYaFdKTzM4Y1kwVnlSM21TaVhNOVJncEV3dlFuNi1aSmlHWjlZSVFBQUFBJCQAAAAAAAAAAAEAAADZcigwz~TO98C0tPO12wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGKMd1hijHdYa; BIDUPSID=888AC44CEB82E828E0858140566F9288; PSTM=1496316421; BAIDUID=13B56673BE48A8F64965C6A879AEE775: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Mp78jR093JO4y4Ldj4oxJp8eWJQ2QJ8BtCI-MxK; delPer=0; PSINO=3; H_PS_PSSID=1447_25810_21099_28329_28131_28267_27244; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; indexPageSugList=%5B%22%E8%A1%97%E6%8B%8D%22%5D; cleanHistoryStatus=0; userFrom=null',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
    urls = []
    for i in params:
        resContent = json.loads(requests.get(
            url, params=i, headers=headers).content.decode("utf-8")).get('data')
        urls.append(resContent)

    return urls


def getImg(datalist, path):
    # x = 0
    for list in datalist:
        for i in list:
            if i.get('thumbURL') != None:
                print('正在下载：%s' % i.get('thumbURL'))
                # path = os.path.join("mypic/", i.get('fromPageTitleEnc'))
                # path = path.replace(' ', '_')
                if not os.path.exists(path):
                    os.mkdir(path)
                # 保存图片
                urllib.request.urlretrieve(
                    i.get('thumbURL'), path+'/'+i.get('fromPageTitleEnc').replace('/', '_').replace('|', '_').replace(':', '_')+'.jpg')
                # x += 1
            else:
                print('图片链接不存在')


if __name__ == '__main__':
    datalist = getDatas('街拍', 2)
    getImg(datalist, 'image')
